/**
 * 优化面板组件
 * 展示文章分析结果和优化建议
 */

import React, { useState, useEffect, useCallback } from 'react';
import {
  Card,
  Tabs,
  Button,
  Progress,
  List,
  Tag,
  Space,
  Tooltip,
  message,
  Spin,
  Badge,
  Row,
  Col,
  Statistic,
  Alert,
  Typography,
  Checkbox,
  Divider,
  Empty
} from 'antd';
import {
  BulbOutlined,
  CheckCircleOutlined,
  WarningOutlined,
  ThunderboltOutlined,
  EditOutlined,
  FileSearchOutlined,
  LinkOutlined,
  PictureOutlined,
  GlobalOutlined,
  ReloadOutlined,
  DownloadOutlined
} from '@ant-design/icons';
import { useOptimizationStore } from '../../stores/optimization.store';
import { optimizationService } from '../../services/optimization.service';
import './OptimizationPanel.css';

const { TabPane } = Tabs;
const { Title, Paragraph, Text } = Typography;

interface OptimizationPanelProps {
  content: string;
  title?: string;
  articleId?: string;
  onContentUpdate?: (content: string) => void;
}

interface SuggestionItem {
  id: string;
  type: string;
  priority: 'high' | 'medium' | 'low';
  description: string;
  detail: string;
  location?: string;
  original_text?: string;
  suggested_text?: string;
  impact_score: number;
  auto_applicable: boolean;
  applied: boolean;
}

const OptimizationPanel: React.FC<OptimizationPanelProps> = ({
  content,
  title,
  articleId,
  onContentUpdate
}) => {
  const {
    currentAnalysis,
    isAnalyzing,
    selectedSuggestions,
    appliedSuggestions,
    setCurrentAnalysis,
    setAnalyzing,
    toggleSuggestion,
    clearSelection,
    addAppliedSuggestion
  } = useOptimizationStore();

  const [activeTab, setActiveTab] = useState('overview');
  const [suggestions, setSuggestions] = useState<SuggestionItem[]>([]);
  const [isApplying, setIsApplying] = useState(false);
  const [optimizedContent, setOptimizedContent] = useState('');
  const [filterPriority, setFilterPriority] = useState<string>('all');

  // optimizationService is now imported, no need to instantiate

  // 执行分析
  const handleAnalyze = useCallback(async () => {
    if (!content) {
      message.warning('请先输入文章内容');
      return;
    }

    setAnalyzing(true);
    try {
      const result = await optimizationService.analyzeContent({
        content,
        title,
        article_id: articleId,
        optimization_types: ['all']
      });

      setCurrentAnalysis(result);
      
      // 获取建议列表
      const suggestionList = await optimizationService.getSuggestions(result.task_id);
      setSuggestions(suggestionList);
      
      message.success('分析完成');
    } catch (error) {
      message.error('分析失败，请重试');
      console.error(error);
    } finally {
      setAnalyzing(false);
    }
  }, [content, title, articleId]);

  // 应用选中的建议
  const handleApplySuggestions = async () => {
    if (selectedSuggestions.length === 0) {
      message.warning('请先选择要应用的建议');
      return;
    }

    if (!currentAnalysis?.task_id) {
      message.error('缺少分析任务ID');
      return;
    }

    setIsApplying(true);
    try {
      let updatedContent = content;

      if (selectedSuggestions.length === 1) {
        // 单个应用
        const result = await optimizationService.applyOptimization({
          task_id: currentAnalysis.task_id,
          suggestion_id: selectedSuggestions[0],
          content: updatedContent
        });
        updatedContent = result.optimized_content;
      } else {
        // 批量应用
        const result = await optimizationService.batchApplyOptimizations({
          task_id: currentAnalysis.task_id,
          suggestion_ids: selectedSuggestions,
          content: updatedContent
        });
        updatedContent = result.optimized_content;
      }

      setOptimizedContent(updatedContent);

      // 标记已应用的建议
      selectedSuggestions.forEach(id => addAppliedSuggestion(id));
      clearSelection();

      message.success(`成功应用 ${selectedSuggestions.length} 条建议`);
      // 不再打开抽屉，直接切换到对比标签页
      setActiveTab('compare');
    } catch (error) {
      message.error('应用建议失败');
      console.error(error);
    } finally {
      setIsApplying(false);
    }
  };

  // 一键自动优化
  const handleAutoOptimize = async () => {
    setIsApplying(true);
    try {
      const result = await optimizationService.autoOptimize({
        content,
        apply_basic_rules: true
      });

      setOptimizedContent(result.optimized_content);
      message.success('自动优化完成');
      // 不再打开抽屉，直接切换到对比标签页
      setActiveTab('compare');
    } catch (error) {
      message.error('自动优化失败');
      console.error(error);
    } finally {
      setIsApplying(false);
    }
  };

  // 确认应用优化内容
  const handleConfirmOptimization = () => {
    if (onContentUpdate && optimizedContent) {
      onContentUpdate(optimizedContent);
      message.success('优化内容已应用到生成区');
      setOptimizedContent('');
      setActiveTab('overview');
    }
  };

  // 导出分析报告
  const handleExportReport = async () => {
    if (!currentAnalysis?.task_id) {
      message.warning('请先执行分析');
      return;
    }

    try {
      const report = await optimizationService.exportAnalysis(currentAnalysis.task_id);
      
      // 创建下载链接
      const blob = new Blob([JSON.stringify(report, null, 2)], { type: 'application/json' });
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `optimization-report-${currentAnalysis.task_id}.json`;
      link.click();
      
      message.success('报告已导出');
    } catch (error) {
      message.error('导出失败');
      console.error(error);
    }
  };

  // 渲染优先级标签
  const renderPriorityTag = (priority: string) => {
    const colorMap: Record<string, string> = {
      high: 'red',
      medium: 'orange',
      low: 'blue'
    };
    return <Tag color={colorMap[priority] || 'default'}>{priority.toUpperCase()}</Tag>;
  };

  // 渲染类型图标
  const renderTypeIcon = (type: string) => {
    const iconMap: Record<string, React.ReactNode> = {
      structure: <FileSearchOutlined />,
      coherence: <LinkOutlined />,
      fluency: <EditOutlined />,
      keyword: <BulbOutlined />,
      title: <GlobalOutlined />,
      image: <PictureOutlined />,
      seo: <GlobalOutlined />
    };
    return iconMap[type] || <BulbOutlined />;
  };

  // 过滤建议
  const filteredSuggestions = suggestions.filter(sug => 
    filterPriority === 'all' || sug.priority === filterPriority
  );

  return (
    <div className="optimization-panel">
      <div className="panel-header" style={{ marginBottom: 16 }}>
        <Space direction="vertical" style={{ width: '100%' }}>
          <Button
            type="primary"
            icon={<ThunderboltOutlined />}
            onClick={handleAnalyze}
            loading={isAnalyzing}
            block
          >
            开始分析
          </Button>
          <Button
            icon={<BulbOutlined />}
            onClick={handleAutoOptimize}
            loading={isApplying}
            disabled={!content}
            block
          >
            一键优化
          </Button>
          {currentAnalysis && (
            <Button
              icon={<DownloadOutlined />}
              onClick={handleExportReport}
              block
            >
              导出报告
            </Button>
          )}
        </Space>
      </div>

      {isAnalyzing && (
        <div className="analyzing-container" style={{ textAlign: 'center', padding: '40px 0' }}>
          <Spin size="large" tip="正在分析文章..." />
        </div>
      )}

      {currentAnalysis && !isAnalyzing && (
        <Tabs activeKey={activeTab} onChange={setActiveTab} size="small">
          <TabPane tab="总览" key="overview">
            <Row gutter={[8, 8]}>
              <Col span={12}>
                <Card size="small">
                  <Statistic
                    title="综合评分"
                    value={currentAnalysis.overall_score * 100}
                    precision={1}
                    suffix="%"
                    valueStyle={{ color: currentAnalysis.overall_score > 0.7 ? '#52c41a' : '#ff4d4f', fontSize: '20px' }}
                  />
                </Card>
              </Col>
              <Col span={12}>
                <Card size="small">
                  <Statistic
                    title="内容长度"
                    value={currentAnalysis.content_length}
                    suffix="字"
                    valueStyle={{ fontSize: '20px' }}
                  />
                </Card>
              </Col>
              <Col span={12}>
                <Card size="small">
                  <Statistic
                    title="建议总数"
                    value={currentAnalysis.suggestions_count}
                    prefix={<BulbOutlined />}
                    valueStyle={{ fontSize: '20px' }}
                  />
                </Card>
              </Col>
              <Col span={12}>
                <Card size="small">
                  <Statistic
                    title="高优先级"
                    value={currentAnalysis.high_priority_count}
                    valueStyle={{ color: '#ff4d4f', fontSize: '20px' }}
                  />
                </Card>
              </Col>
            </Row>

            <Card style={{ marginTop: 16 }} title="各维度评分" size="small">
              <Space direction="vertical" style={{ width: '100%' }} size="small">
                {currentAnalysis.scores && Object.entries(currentAnalysis.scores).map(([key, value]) => (
                  <div key={key}>
                    <Text style={{ fontSize: '12px' }}>{key}:</Text>
                    <Progress
                      percent={(value as number || 0) * 100}
                      status={value && value > 0.7 ? 'success' : 'normal'}
                      format={percent => `${percent?.toFixed(1)}%`}
                      size="small"
                    />
                  </div>
                ))}
              </Space>
            </Card>
          </TabPane>

            <TabPane tab={<Badge count={suggestions.length}>建议</Badge>} key="suggestions">
              <div className="suggestions-toolbar" style={{ marginBottom: 12 }}>
                <Space direction="vertical" style={{ width: '100%' }} size="small">
                  <div>
                    <Text style={{ fontSize: '12px', marginRight: 8 }}>优先级：</Text>
                    <Button.Group size="small">
                      <Button
                        type={filterPriority === 'all' ? 'primary' : 'default'}
                        onClick={() => setFilterPriority('all')}
                      >
                        全部
                      </Button>
                      <Button
                        type={filterPriority === 'high' ? 'primary' : 'default'}
                        onClick={() => setFilterPriority('high')}
                      >
                        高
                      </Button>
                      <Button
                        type={filterPriority === 'medium' ? 'primary' : 'default'}
                        onClick={() => setFilterPriority('medium')}
                      >
                        中
                      </Button>
                      <Button
                        type={filterPriority === 'low' ? 'primary' : 'default'}
                        onClick={() => setFilterPriority('low')}
                      >
                        低
                      </Button>
                    </Button.Group>
                  </div>

                  {selectedSuggestions.length > 0 && (
                    <Space style={{ width: '100%', justifyContent: 'space-between' }}>
                      <Text style={{ fontSize: '12px' }}>已选 {selectedSuggestions.length} 项</Text>
                      <Space size="small">
                        <Button onClick={clearSelection} size="small">清除</Button>
                        <Button
                          type="primary"
                          onClick={handleApplySuggestions}
                          loading={isApplying}
                          size="small"
                          icon={<CheckCircleOutlined />}
                        >
                          应用
                        </Button>
                      </Space>
                    </Space>
                  )}
                </Space>
              </div>

              <List
                className="suggestions-list"
                size="small"
                dataSource={filteredSuggestions}
                renderItem={(item) => (
                  <List.Item
                    key={item.id}
                    className={`suggestion-item ${appliedSuggestions.includes(item.id) ? 'applied' : ''}`}
                    style={{ padding: '8px 0' }}
                    actions={[
                      appliedSuggestions.includes(item.id) ? (
                        <Tag color="green" style={{ fontSize: '11px' }}>已应用</Tag>
                      ) : (
                        <Checkbox
                          checked={selectedSuggestions.includes(item.id)}
                          onChange={() => toggleSuggestion(item.id)}
                        />
                      )
                    ]}
                  >
                    <List.Item.Meta
                      avatar={renderTypeIcon(item.type)}
                      title={
                        <Space size="small" wrap>
                          {renderPriorityTag(item.priority)}
                          <Text strong style={{ fontSize: '13px' }}>{item.description}</Text>
                          {item.auto_applicable && (
                            <Tag color="blue" style={{ fontSize: '11px' }}>可自动</Tag>
                          )}
                        </Space>
                      }
                      description={
                        <div style={{ fontSize: '12px' }}>
                          <Paragraph style={{ marginBottom: 4, fontSize: '12px' }}>{item.detail}</Paragraph>
                          {item.location && (
                            <Text type="secondary" style={{ fontSize: '11px' }}>位置：{item.location}</Text>
                          )}
                          {item.original_text && item.suggested_text && (
                            <div className="suggestion-preview" style={{ marginTop: 4 }}>
                              <Text delete style={{ fontSize: '11px' }}>{item.original_text}</Text>
                              <br />
                              <Text mark style={{ fontSize: '11px' }}>{item.suggested_text}</Text>
                            </div>
                          )}
                          <div style={{ marginTop: 4 }}>
                            <Text type="secondary" style={{ fontSize: '11px' }}>影响：</Text>
                            <Progress
                              percent={item.impact_score * 100}
                              steps={5}
                              size="small"
                              style={{ width: 80, display: 'inline-block', marginLeft: 4 }}
                              showInfo={false}
                            />
                          </div>
                        </div>
                      }
                    />
                  </List.Item>
                )}
                locale={{ emptyText: <Empty description="暂无建议" image={Empty.PRESENTED_IMAGE_SIMPLE} /> }}
              />
            </TabPane>

            <TabPane tab="对比" key="compare">
              {optimizedContent ? (
                <div className="compare-container">
                  <Alert
                    message="优化完成"
                    description="以下是优化后的内容预览"
                    type="success"
                    showIcon
                    style={{ marginBottom: 12 }}
                    closable
                  />

                  <Space direction="vertical" style={{ width: '100%' }} size="small">
                    <Card title="原始内容" size="small" headStyle={{ fontSize: '13px' }}>
                      <Paragraph
                        className="content-preview"
                        style={{ fontSize: '12px', marginBottom: 0, maxHeight: '150px', overflow: 'auto' }}
                        ellipsis={{ rows: 6, expandable: true, symbol: '展开' }}
                      >
                        {content}
                      </Paragraph>
                    </Card>

                    <Card title="优化后" size="small" headStyle={{ fontSize: '13px' }}>
                      <Paragraph
                        className="content-preview"
                        style={{ fontSize: '12px', marginBottom: 0, maxHeight: '150px', overflow: 'auto' }}
                        ellipsis={{ rows: 6, expandable: true, symbol: '展开' }}
                      >
                        {optimizedContent}
                      </Paragraph>
                    </Card>

                    <Button
                      type="primary"
                      onClick={handleConfirmOptimization}
                      block
                      icon={<CheckCircleOutlined />}
                    >
                      应用优化内容
                    </Button>
                  </Space>
                </div>
              ) : (
                <Empty
                  description="请先应用优化建议"
                  image={Empty.PRESENTED_IMAGE_SIMPLE}
                />
              )}
            </TabPane>
          </Tabs>
        )}
    </div>
  );
};

export default OptimizationPanel;